//
//  FXCHomeTableViewController.m
//  XinLangFeiBo
//
//  Created by dllo on 16/2/26.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "FXCHomeTableViewController.h"

#import "FXCStatus.h"
#import "FXCAccount.h"

#import "FXCSecondHome.h"

#import <UITableView+SDAutoTableViewCellHeight.h>
#import <MJRefresh.h>


#import "FXCStatusFrame.h"
#import "FXCStatusCell.h"

#import "FXCDetailViewController.h"

#import "FXCToolBarView.h"

#import "FXCcommentController.h"

#import "FXCNetworking.h"

#import "FXCStatusCacheTool.h"

@interface FXCHomeTableViewController ()<UITableViewDelegate, UITableViewDataSource>



@property (nonatomic, strong) FXCToolBarView *toolBarView;


@end

@implementation FXCHomeTableViewController



- (NSMutableArray *)arrModel{
    if (_arrModel == nil) {
        _arrModel = [NSMutableArray array];
    }
    return _arrModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self creatTabelView];
    
    //    左按钮
//    UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(clickLeft)];
//    self.navigationItem.leftBarButtonItem = leftBtn;
    //    右按钮
    UIButton *composeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [composeBtn setTitle:@"发微博" forState:UIControlStateNormal];
    
    [composeBtn sizeToFit];
    [composeBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    
    [composeBtn addTarget:self action:@selector(clickRight) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *composeItem = [[UIBarButtonItem alloc] initWithCustomView:composeBtn];
    
    self.navigationItem.rightBarButtonItem = composeItem;
    
//    添加刷新控件
    [self setUpRefreshView];
    
//    开始刷新
    [self loadNewStatuses];
    
//    添加观察者
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(commentBtn:) name:@"FXCcomment" object:nil];

}



- (void)commentBtn:(NSNotification*)aNotification{
    NSNumber *ID = [aNotification object];
    FXCcommentController *commentvc = [[FXCcommentController alloc] init];
    
    commentvc.Id = [ID longLongValue];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:commentvc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

//移除观察者
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(commentBtn:) name:@"FXCcomment" object:nil];
}

- (void)creatTabelView{
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

- (void)clickLeft{
    
}

- (void)clickRight{
    FXCDetailViewController *detail = [[FXCDetailViewController alloc] init];
//    push时消失 back时回来
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
    
    self.hidesBottomBarWhenPushed = NO;
    
}

//    添加刷新控件
- (void)setUpRefreshView{

    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewStatuses];
    }];

    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreStatues];
    }];
}



// 下拉刷新

- (void)loadNewStatuses{
    FXCStatusFrame *statusF = [self.arrModel firstObject];
    id sinceID = @"0";
    if (statusF.status.idstr) {
        sinceID = @([statusF.status.idstr longLongValue]);
//        NSLog(@"%@", sinceID);
    }
    NSDictionary *param = @{@"since_id":sinceID};
    
//    先从缓存中获取数据
    NSArray *statuses = [FXCStatusCacheTool statusesWithParam:param];
    if (statuses.count) {
        for (FXCStatus *status in statuses) {
            FXCStatusFrame *statusF = [[FXCStatusFrame alloc] init];
            statusF.status = status;
            [self.arrModel addObject:statusF];
        }
//        不需要再发送请求
        return;
    }
    
    
    
    [FXCNetworking getWithURL:@"https://open.weibo.cn/2/statuses/friends_timeline.json" parameter:param success:^(id responseObject) {
        NSMutableArray *arr = [NSMutableArray array];
//        缓存数据
        [FXCStatusCacheTool saveWithStatus:responseObject[@"statuses"]];
        
        for (NSDictionary *dicM in responseObject[@"statuses"]) {
            
            
            FXCStatus *model = [FXCStatus mj_objectWithKeyValues:dicM];
            FXCStatusFrame *statusF = [[FXCStatusFrame alloc] init];
            statusF.status = model;
            [arr addObject:statusF];
            
        }
        ////    插入最新数据
        NSInteger count = arr.count;
        
        [self.arrModel insertObjects:arr atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, count)]];
        
        //        [self.arrModel addObjectsFromArray:arr];
        
        [self.tableView reloadData];
        
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        NSLog(@"%@", error);
        
        
        
    }];

    
}

//上拉加载更多


- (void)loadMoreStatues{
    FXCStatusFrame *statusf = [self.arrModel lastObject];
    id maxID = @"0";
    if (statusf.status.idstr) {
        maxID = @([statusf.status.idstr longLongValue] - 1);
    }
    
    

    NSDictionary *param = @{@"since_id":maxID};
    
    
//    //    先从缓存中获取数据
//    NSArray *statuses = [FXCStatusCacheTool statusesWithParam:param];
//    if (statuses.count) {
//        for (FXCStatus *status in statuses) {
//            FXCStatusFrame *statusF = [[FXCStatusFrame alloc] init];
//            statusF.status = status;
//            [self.arrModel addObject:statusF];
//        }
//        //        不需要再发送请求
//        return;
//    }
//    
    [FXCNetworking getWithURL:@"https://open.weibo.cn/2/statuses/friends_timeline.json" parameter:param success:^(id responseObject) {
        
        //        缓存数据
        [FXCStatusCacheTool saveWithStatus:responseObject[@"statuses"]];
        
        for (NSDictionary *dicM in responseObject[@"statuses"]) {
            
            
            FXCStatus *model = [FXCStatus mj_objectWithKeyValues:dicM];
            FXCStatusFrame *statusF = [[FXCStatusFrame alloc] init];
            statusF.status = model;
            [self.arrModel addObject:statusF];
            
        }
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        
       
    } failure:^(NSError *error) {
        NSLog(@"%@", error);
    }];
    
}


#pragma mark - Table view data source



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.arrModel.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    创建cell
    static NSString *ID = @"cell";
    
    FXCStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (cell == nil) {
        cell = [[FXCStatusCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }

    FXCStatusFrame *statusF = self.arrModel[indexPath.row];
    
    cell.statusF = statusF;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    FXCStatusFrame *statusF = self.arrModel[indexPath.row];
    
    
    return statusF.cellHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    FXCAccount *account = [NSKeyedUnarchiver unarchiveObjectWithFile:FXCAccountFile];
    FXCStatusFrame *statusF = self.arrModel[indexPath.row];
    FXCSecondHome *secondHome = [[FXCSecondHome alloc] init];
    secondHome.Id = statusF.status.id;
    secondHome.uid = statusF.status.user.id;
    secondHome.access_token = account.access_token;
    secondHome.statusF = statusF;
    
    
    [self.navigationController pushViewController:secondHome animated:YES];
//    self.hidesBottomBarWhenPushed = NO;
    
}


@end
